package com.service.totalauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.service.config.annotation.Log;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.utils.*;
import com.service.totalauth.dao.*;
import com.service.totalauth.dto.AuthorizationDto;
import com.service.totalauth.dto.PhoneNumber;
import com.service.totalauth.dto.WeiChatDto;
import com.service.totalauth.dto.WeiChatResponseDto;
import com.service.totalauth.entity.*;
import com.service.totalauth.service.AuthorizationUserService;
import com.service.totalauth.service.PortalUserService;
import com.service.totalauth.service.UserAuthLogService;
import com.service.totalauth.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.service.config.constant.ApiUrlConstants.*;
import static com.service.config.constant.Constant.*;
import static com.service.config.utils.CharUtil.getCharAndNumr;
import static com.service.config.utils.DesUtil.decodeToString;
import static com.service.config.utils.DesUtil.decodeUrlToString;

/**
 * 授权终端用户认证表(AuthorizationUser)表服务实现类
 *
 * @author makejava
 * @since 2021-12-03 09:38:43
 */
@Service("authorizationUserService")
public class AuthorizationUserServiceImpl implements AuthorizationUserService {
    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationUserServiceImpl.class);

    @Resource
    private AuthorizationUserDao authorizationUserDao;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ProgrammeApiBindDao programmeApiBindDao;
    @Resource
    RestTemplate restTemplate;
    @Resource
    QueryWeiChatServiceImpl queryWeiChatService;
    @Resource
    private UserAuthLogService userAuthLogService;
    @Resource
    private UserAuthLogDao userAuthLogDao;
    @Value("${spring.fileSeverDomain}")
    private String fileSeverDomain;
    @Value("${spring.nginxUrl}")
    private String nginxUrl;
    @Resource
    private ManageProgrammeInfoDao manageProgrammeInfoDao;
    @Resource
    private PortalUserService portalUserService;
    @Resource
    private QueryMiniProgrammeServiceImpl queryMiniProgrammeService;
    @Resource
    private CompanyInfoDao companyInfoDao;
    @Resource
    private CloudCampusApi cloudCampusApi;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AuthorizationUser queryById(String id) {
        return this.authorizationUserDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<AuthorizationUser> queryAllByLimit(int offset, int limit) {
        return this.authorizationUserDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param authorizationUser 实例对象
     * @return 实例对象
     */
    @Override
    public AuthorizationUser insert(AuthorizationUser authorizationUser) {
        this.authorizationUserDao.insert(authorizationUser);
        return authorizationUser;
    }

    /**
     * 修改数据
     *
     * @param authorizationUser 实例对象
     * @return 实例对象
     */
    @Override
    public AuthorizationUser update(AuthorizationUser authorizationUser) {
        this.authorizationUserDao.update(authorizationUser);
        return this.queryById(authorizationUser.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.authorizationUserDao.deleteById(id) > 0;
    }

    /**
     * 解密数据获取用户手机号
     * @param code
     * @param programmeInfoBindId
     * @return
     * @throws Exception
     */
    @Override
    public Result decrypt(String code,String programmeInfoBindId,String redisToken,String bAuthToken,String nickName,String phoneCode) throws Exception {
        Map<String,Object> map3=new HashMap<>();
        ProgrammeApiBind programmeApiBind = programmeApiBindDao.queryById(programmeInfoBindId);
        if (null == programmeApiBind)
        {
            return Result.failure("传递参数有误，请确认方案绑定id");
        }
        CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());

        if(!redisUtil.exist(redisToken))
        {
            return Result.failure("参数已失效，请重新登录portal页面!");
        }
        AuthorizationDto authorizationDto=ModelMapperUtil.strictMap(redisUtil.getValue(redisToken),AuthorizationDto.class);
        //判断是否是第一次登录微信小程序获取登录信息
        Map<String,Object> map1 = new HashMap();
        if (bAuthToken==null || bAuthToken.equals("") || !redisUtil.exist(bAuthToken) ) {
            map1 = getResult2(programmeInfoBindId, code, "", companyInfo.getAppId(), companyInfo.getSecret());
            if (map1.containsKey("errcode")){
                return Result.failure(map1.get("errcode").toString());
            }
            bAuthToken=map1.get("Token").toString();
        }
        String value = redisUtil.getValue(bAuthToken);
        Map<String, Object> map2 = JsonXMLUtils.json2map(value);
        String phoneNumber = getPhoneNumber(companyInfo, phoneCode);
        if (phoneNumber == null || phoneNumber.equals(""))
        {
            map2.put("errorMsg","code码已失效，请重新获取code");
            Result.failure(JsonXMLUtils.obj2json(map2));
        }

        authorizationDto.setType(3);
        authorizationDto.setNickName(nickName);
        authorizationDto.setPhoneNum(phoneNumber);
        redisUtil.set(redisToken,1,JsonXMLUtils.obj2json(authorizationDto),5);

        map3.put("wxToken",bAuthToken);
        map3.put("authorizationDto",authorizationDto);
        return Result.ok().setData(map3);
    }

    private Map<String,Object> getResult2(String programmeInfoBindId,String code, String url, String customerAppId, String customerSecret) throws Exception {
        Map<String,Object> map=new HashMap<>();
        LOG.info("9");
        HashMap map1 = queryWeiChatService.getOpenId(queryWeiChatService.getUrlWenXin(code,url, customerAppId, customerSecret));
        if (map1.containsKey("errcode")){
            map.put("errcode","用户登录失败，请检查参数!");
            return map;
        }
        Object weiChatDto1 = map1.get("weiChatDto");
        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        WeiChatDto weiChatDto2 = ModelMapperUtil.strictMap(map2, WeiChatDto.class);
        String token = UserTokenManager.generateToken(programmeInfoBindId);
        redisUtil.set(token,4, JsonXMLUtils.obj2json(JsonXMLUtils.json2map(map1.get("weiChatDto").toString())),2);
        LOG.info("10");
        map.put("Token",token);
        return map;
    }

    @Override
    public Result getAuthorizationDetail(String redisToken) {
        if (!redisUtil.exist(redisToken))
        {
            return Result.failure("token已失效");
        }
        Map<String,Object> map=new HashMap<>();
        String wxValue = redisUtil.getValue(redisToken);
        AuthorizationDto authorizationDto = ModelMapperUtil.strictMap(wxValue, AuthorizationDto.class);

        map.put("nickName",authorizationDto.getNickName());
        map.put("phoneNum",authorizationDto.getPhoneNum());
        return Result.ok().setData(map);
    }

    @Override
    public Result getCodeDetail(String wxToken, String redisToken, String qyToken,String code) throws Exception {
        if (!redisUtil.exist(redisToken) || !redisUtil.exist(wxToken))
        {
            return Result.failure("token已失效");
        }
        Map<String,Object> map=new HashMap<>();
        String redisValue = redisUtil.getValue(redisToken);
        String wxValue = redisUtil.getValue(wxToken);
        if (redisValue==null || wxValue==null)
        {
            return Result.failure("token缓存已失效");
        }
        AuthorizationDto authorizationDto = ModelMapperUtil.strictMap(redisValue, AuthorizationDto.class);
        WeiChatDto weiChatDto = ModelMapperUtil.strictMap(wxValue, WeiChatDto.class);

        if (qyToken==null || "".equals(qyToken))
        {
            authorizationDto.setCode(code);
            Result qyWeChatResult = getQYWeChatResult(qyToken, authorizationDto,0);
            qyToken= (String) qyWeChatResult.getData();
        }
        String qyValue = redisUtil.getValue(qyToken);
        QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(qyValue, QyWeiChatUserDetailVo.class);

        map.put("authorizationDto",authorizationDto);
        map.put("weiChatDto",weiChatDto);
        map.put("qyWeiChatUserDetailVo",qyWeiChatUserDetailVo);
        return Result.ok().setData(map);
    }
    /**
     * 弹出portal页面，点击跳转微信小程序，然后分享微信小程序到企业微信的一个聊天窗口，
     * 在聊天窗口中点击分享的链接，完成认证(这个方案中，参数是可以传递过来的，
     * 当然也可以不使用传递来的参数，直接使用无参数方案
     * 此方法为无参数方案
     * @param bAuthToken
     * @param authorizationDto
     * @return
     * @throws Exception
     */
    @Override
    public Result checkQyWeiUser(AuthorizationDto authorizationDto,String bAuthToken,String wxAuth) throws Exception {
        authorizationDto.setSsid(DesUtil.encodeToString(authorizationDto.getSsid()));
        if (bAuthToken != null && !bAuthToken.equals("")) {
            if (!redisUtil.exist(bAuthToken) ) { //未使用过该小程序
                return getResult(bAuthToken,authorizationDto,wxAuth);
            }
            /**
             * 企业微信客户使用过该小程序
             */
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = JsonXMLUtils.json2obj(redisUtil.getValue(bAuthToken), QyWeiChatUserDetailVo.class);
            if (qyWeiChatUserDetailVo.getUserid() != null) {
                //获取方案，微信账号，云管账号绑定关系
                ProgrammeApiBind programmeApiBind = new ProgrammeApiBind();
                if (StringUtils.isEmpty(authorizationDto.getProgrammeInfoBindId())) {
                    programmeApiBind =  getProgrammeApiBindByWxAuth(wxAuth);
                }else {
                    programmeApiBind = getProgrammeApiBind(authorizationDto);
                }
                if (programmeApiBind == null) {
                    return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
                }
                //查询微信账号和企业微信账号
                CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
                if (companyInfo == null) {
                    return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
                }
                /**
                 * 发起认证
                 */
                authorizationDto.setType(3);
                authorizationDto.setProgrammeInfoBindId(programmeApiBind.getId());
                Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,3);
                if (auth.getCode() == 200) {
                    Map map = new HashMap();
                    redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                    //认证结果
                    redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                    map.put("token",bAuthToken);
                    return Result.ok().setData(map);
                }
                return auth;
            }
            ProgrammeApiBind programmeApiBind = new ProgrammeApiBind();
            if (StringUtils.isEmpty(authorizationDto.getProgrammeInfoBindId())) {
                programmeApiBind =  getProgrammeApiBindByWxAuth(wxAuth);
            }else {
                programmeApiBind = getProgrammeApiBind(authorizationDto);
            }
            if (programmeApiBind == null) {
                return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
            }
            CompanyInfo miniCompanyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
            if (miniCompanyInfo == null) {
                return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
            }
            CompanyInfo companyInfo = companyInfoDao.queryById(miniCompanyInfo.getCompanyInfoId());
            if (companyInfo == null) {
                return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
            }
            //访客突然成为企业微信的员工则需要查询其身份并授权
            authorizationDto.setProgrammeInfoBindId(programmeApiBind.getId());
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            return Result.failure("你不是该企业的员工");
        }else {
            bAuthToken = UserTokenManager.generateToken(authorizationDto.getCode());// 新增用户
            return getResult(bAuthToken, authorizationDto,wxAuth);
        }

    }

    private ProgrammeApiBind getProgrammeApiBindByWxAuth(String wxAuth) {
        ProgrammeApiBind programmeApiBind = programmeApiBindDao.queryByWxAuth(wxAuth);
        if(null==programmeApiBind)
        {
            return null;
        }
        if(programmeApiBind.getCompanyInfoId()==null ||"".equals(programmeApiBind.getCompanyInfoId()))
        {
            return null;
        }
        return programmeApiBind;
    }

    private Result getResult(String bAuthToken, AuthorizationDto authorizationDto,String wxAuth) throws Exception {
        ProgrammeApiBind programmeApiBind = new ProgrammeApiBind();
        if (StringUtils.isEmpty(authorizationDto.getProgrammeInfoBindId())) {
            programmeApiBind =  getProgrammeApiBindByWxAuth(wxAuth);
        }else {
            programmeApiBind = getProgrammeApiBind(authorizationDto);
        }
        if (programmeApiBind == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        authorizationDto.setProgrammeInfoBindId(programmeApiBind.getId());
        CompanyInfo miniCompanyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
        if (miniCompanyInfo == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        CompanyInfo companyInfo = companyInfoDao.queryById(miniCompanyInfo.getCompanyInfoId());
        if (companyInfo == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        String url = queryWeiChatService.getUrl("", companyInfo.getAppId(), companyInfo.getSecret());
        HashMap openId = queryWeiChatService.getOpenId(url);
        if (openId.containsKey("errcode")) {
            return Result.ok().setData(openId);
        }
        Object weiChatDto1 = openId.get("weiChatDto");
        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(map2, WeiChatVo.class);
        openId = queryWeiChatService.getUserInfo(weiChatVo.getAccess_token(), authorizationDto.getCode());
        if (openId.containsKey("errcode")){
            return Result.ok().setData(openId);
        }
        weiChatDto1 = openId.get("qyWeiChatUserVo");
        map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        QyWeiChatUserVo qyWeiChatUserVo1 = ModelMapperUtil.strictMap(map2, QyWeiChatUserVo.class);
        if (qyWeiChatUserVo1.getUserid() != null) {
            openId = queryWeiChatService.getUser(weiChatVo.getAccess_token(), qyWeiChatUserVo1.getUserid());
            if (openId.containsKey("errcode")){
                return Result.ok().setData(openId);
            }
            weiChatDto1 = openId.get("qyWeiChatUserDetailVo");
            map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(map2, QyWeiChatUserDetailVo.class);
            qyWeiChatUserDetailVo.setAccess_token(weiChatVo.getAccess_token());
            qyWeiChatUserDetailVo.setDeviceId("1");
            qyWeiChatUserDetailVo.setStatus(true);
            qyWeiChatUserDetailVo.setQyCorpInfoId(companyInfo.getId());
            qyWeiChatUserDetailVo.setPortalUserId(programmeApiBind.getPortalUserId());
            authorizationDto.setType(3);
            Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,3);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        } else {
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = new QyWeiChatUserDetailVo();
            qyWeiChatUserDetailVo.setStatus(false);
            qyWeiChatUserDetailVo.setDeviceId("2");
            qyWeiChatUserDetailVo.setName("非企业员工");
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            return Result.failure("你不是该企业的员工");
        }
    }
    /**
     * 检测员工身份以及授权员工使用该网络
     * @param bAuthToken
     * @return
     * @throws Exception
     */
    @Override
    public Result checkUserByQYWeChat(String code,String redisToken,String bAuthToken, Integer time,Boolean isAuth) throws Exception {
        LOG.info("code:"+code+";redisToken:"+redisToken+";bAuthToken:"+bAuthToken+";time"+time+";isAuth:"+isAuth);
        if(!isAuth)
        {
            if (redisUtil.exist(redisToken)) {
                redisUtil.delete(redisToken);
                Map<String,String> map=new HashMap<>();
                map.put("reject success","当前申请以驳回");
                return Result.ok().setData(map);
            }
            return Result.failure(PARAMETER_NOT_FOUND,"认证参数已失效0，请重新获取");
        }
        if (bAuthToken != null && !bAuthToken.equals("")) {
            if (!redisUtil.exist(bAuthToken) ) {
                if (redisUtil.exist(redisToken)) {
                    String value = redisUtil.getValue(redisToken);
                    AuthorizationDto authorizationDto = JsonXMLUtils.json2obj(value, AuthorizationDto.class);
                    authorizationDto.setCode(code);

                    authorizationDto.setType(3);

                    redisUtil.set(redisToken,1,JsonXMLUtils.obj2json(authorizationDto),5);
                    return getQYWeChatResult(bAuthToken,authorizationDto,time);
                }
                return Result.failure(PARAMETER_NOT_FOUND,"认证参数已失效1，请重新获取");
            }
            if (!redisUtil.exist(redisToken)) {
                return Result.failure(PARAMETER_NOT_FOUND,"认证参数已失效2，请重新获取");
            }
            String value = redisUtil.getValue(redisToken);
            AuthorizationDto authorizationDto = JsonXMLUtils.json2obj(value, AuthorizationDto.class);
            authorizationDto.setCode(code);

            authorizationDto.setType(3);

            redisUtil.set(redisToken,1,JsonXMLUtils.obj2json(authorizationDto),5);
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = JsonXMLUtils.json2obj(redisUtil.getValue(bAuthToken), QyWeiChatUserDetailVo.class);
            if (qyWeiChatUserDetailVo.getUserid() != null) {
                ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
                CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
                Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,time);
                if (auth.getCode() == 200) {
                    Map map = new HashMap();
                    redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                    //认证结果
                    redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                    map.put("token",bAuthToken);
                    return Result.ok().setData(map);
                }
                return auth;
            }
            ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
            CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
            //访客突然成为企业微信的员工则需要查询其身份并授权
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            return Result.failure("你不是该企业的员工");
        }else {
            bAuthToken = UserTokenManager.generateToken(code);// 新增用户
            if (!redisUtil.exist(redisToken)) {
                return Result.failure(PARAMETER_NOT_FOUND,"参数已失效，请重新获取");
            }
            String value = redisUtil.getValue(redisToken);
            AuthorizationDto authorizationDto = JsonXMLUtils.json2obj(value, AuthorizationDto.class);
            authorizationDto.setCode(code);

            authorizationDto.setType(3);

            redisUtil.set(redisToken,1,JsonXMLUtils.obj2json(authorizationDto),5);
            LOG.info(JsonXMLUtils.obj2json(authorizationDto));
            return getQYWeChatResult(bAuthToken, authorizationDto,time);
        }
    }

    private Result getQYWeChatResult(String bAuthToken, AuthorizationDto authorizationDto,Integer time) throws Exception {
        ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
        CompanyInfo miniCompanyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
        if (miniCompanyInfo == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        CompanyInfo companyInfo = companyInfoDao.queryById(miniCompanyInfo.getCompanyInfoId());
        if (companyInfo == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }

        String url = queryWeiChatService.getUrl("", companyInfo.getAppId(), companyInfo.getSecret());
        HashMap openId = queryWeiChatService.getOpenId(url);
        if (openId.containsKey("errcode")) {
            return Result.ok().setData(openId);
        }
        Object weiChatDto1 = openId.get("weiChatDto");
        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(map2, WeiChatVo.class);
        openId = queryWeiChatService.getUserInfo(weiChatVo.getAccess_token(), authorizationDto.getCode());
        if (openId.containsKey("errcode")){
            LOG.info("get userInfo error!!!"+openId);
            return Result.ok().setData(openId);
        }
        weiChatDto1 = openId.get("qyWeiChatUserVo");
        map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        QyWeiChatUserVo qyWeiChatUserVo1 = ModelMapperUtil.strictMap(map2, QyWeiChatUserVo.class);
        if (qyWeiChatUserVo1.getUserid() != null) {
            openId = queryWeiChatService.getUser(weiChatVo.getAccess_token(), qyWeiChatUserVo1.getUserid());
            if (openId.containsKey("errcode")){
                return Result.ok().setData(openId);
            }
            weiChatDto1 = openId.get("qyWeiChatUserDetailVo");
            map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(map2, QyWeiChatUserDetailVo.class);
            qyWeiChatUserDetailVo.setAccess_token(weiChatVo.getAccess_token());
            qyWeiChatUserDetailVo.setDeviceId("1");
            qyWeiChatUserDetailVo.setStatus(true);
            qyWeiChatUserDetailVo.setQyCorpInfoId(companyInfo.getId());
            qyWeiChatUserDetailVo.setPortalUserId(programmeApiBind.getPortalUserId());
            Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,time);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        } else {
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = new QyWeiChatUserDetailVo();
            qyWeiChatUserDetailVo.setStatus(false);
            qyWeiChatUserDetailVo.setDeviceId("2");
            qyWeiChatUserDetailVo.setName("非企业员工");
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            return Result.failure("你不是该企业的员工");
        }
    }

    /**
     * 授权 1--飞书 2--钉钉 6--qq认证 7--支付宝认证 用户认证
     * @param bAuthToken
     * @param authorizationDto
     * @return
     * @throws Exception
     */
    @Override
    public Result checkUser(String bAuthToken, AuthorizationDto authorizationDto) throws Exception {
        if (bAuthToken != null && !bAuthToken.equals("")) {
            if (!redisUtil.exist(bAuthToken) ) {
                return getMiniProgrammeResult(bAuthToken,authorizationDto);
            }
            Object object = JsonXMLUtils.json2obj(redisUtil.getValue(bAuthToken), Object.class);
            ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
            if(null==programmeApiBind)
            {
                return Result.failure("参数错误");
            }
            CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
            if (companyInfo == null) {
                return Result.failure("未查到企业信息");
            }
            Result auth = auth(object, authorizationDto, companyInfo,0);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(object),2);
                //认证结果
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        }else {
            // 新增用户
            bAuthToken = UserTokenManager.generateToken(authorizationDto.getCode());
            return getMiniProgrammeResult(bAuthToken, authorizationDto);
        }
    }

    private Result getMiniProgrammeResult(String bAuthToken,AuthorizationDto authorizationDto) throws Exception {
        if (authorizationDto.getProgrammeInfoBindId() == null || authorizationDto.getProgrammeInfoBindId().equals("")) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound); // 参数错误
        }
        ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
        if (programmeApiBind == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
        if (companyInfo == null) {
            return Result.failure("未查到企业信息");
        }
        Integer miniType=authorizationDto.getType();
        String accessTokenUrl="";
        switch (miniType)
        {
            case 1:
                //获取飞书accessToken的url
                accessTokenUrl = getLarkAccessTokenUrl();
                break;
            case 2:
                //获取钉钉accessToken的url
                accessTokenUrl = getDingAccessTokenUrl(companyInfo.getAppId(),companyInfo.getSecret());
                break;
            case 6:
                //获取qq的accessToken的url
                accessTokenUrl = getQQAccessTokenUrl(companyInfo.getAppId(),companyInfo.getSecret());
                break;
            case 7:
                //获取支付宝的accessToken
                return authAli(authorizationDto,bAuthToken,companyInfo,programmeApiBind);
            default:
                return Result.failure("请求参数有误");
        }
        if (accessTokenUrl==null || "".equals(accessTokenUrl))
        {
            return Result.failure("请求参数有误");
        }
        //获取accessToken
        HashMap dataMap = queryMiniProgrammeService.getAccessToken(accessTokenUrl, miniType,companyInfo.getAppId(),companyInfo.getSecret());
        if (dataMap.containsKey("errcode")) {
            return Result.ok().setData(dataMap);
        }
        Object object = dataMap.get("accessToken");
        Map<String, Object> map2 = JsonXMLUtils.json2map(object.toString());

        if (miniType==1)
        {
            //飞书认证
            return authLark(map2,authorizationDto,bAuthToken,companyInfo,programmeApiBind);
        }else if(miniType==2)
        {
            //钉钉认证
            return authDing(map2,authorizationDto,bAuthToken,companyInfo,programmeApiBind);
        }else if (miniType == 6)
        {
            //qq认证
            return authQQ(map2,authorizationDto,bAuthToken,companyInfo,programmeApiBind);
        }
        return Result.failure("请求参数有误");
    }

    /**
     * 获取飞书access_token的url
     * @return
     */
    private String getLarkAccessTokenUrl()
    {
        return queryMiniProgrammeService.getAccessTokenUrl("","","",1);
    }

    /**
     * 获取钉钉access_token的url
     * @param appId
     * @param secret
     * @return
     */
    private String getDingAccessTokenUrl(String appId,String secret)
    {
        return queryMiniProgrammeService.getAccessTokenUrl("",appId,secret,2);
    }

    /**
     * 获取qq的access_token的url
     * @param appId
     * @param secret
     * @return
     */
    private String getQQAccessTokenUrl(String appId,String secret)
    {
        return queryMiniProgrammeService.getAccessTokenUrl("",appId,secret,6);
    }

    /**
     * 认证飞书小程序
     * @param map2
     * @param authorizationDto
     * @param bAuthToken
     * @param companyInfo
     * @param programmeApiBind
     * @return
     * @throws Exception
     */
    private Result authLark(Map<String, Object> map2,AuthorizationDto authorizationDto,String bAuthToken,CompanyInfo companyInfo,ProgrammeApiBind programmeApiBind) throws Exception {
        LarkVo larkVo = ModelMapperUtil.strictMap(map2, LarkVo.class);
        HashMap dataMap = queryMiniProgrammeService.code2Session(larkVo.getApp_access_token(), authorizationDto.getCode(),1,"","");
        if (dataMap.containsKey("errcode")){
            return Result.ok().setData(dataMap);
        }
        Object object = dataMap.get("userVo");
        map2 = JsonXMLUtils.json2map(object.toString());
        LarkUserVo larkUserVo = ModelMapperUtil.strictMap(map2, LarkUserVo.class);
        if (larkUserVo.getData().get("open_id") != null) {
            dataMap = queryMiniProgrammeService.getUserInfo(larkUserVo.getData().get("access_token"), larkUserVo.getData().get("open_id"),1);
            if (dataMap.containsKey("errcode")){
                return Result.ok().setData(dataMap);
            }
            object = dataMap.get("userDetailInfo");
            map2 = JsonXMLUtils.json2map(object.toString());
            LarkUserDetailInfo larkUserDetailInfo = ModelMapperUtil.strictMap(map2, LarkUserDetailInfo.class);
            larkUserDetailInfo.setStatus(true);
            Result auth = auth(larkUserDetailInfo, authorizationDto, companyInfo,0);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(larkUserDetailInfo),2);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(larkUserDetailInfo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        } else {
            LarkUserDetailInfo larkUserDetailInfo = new LarkUserDetailInfo();
            larkUserDetailInfo.setStatus(false);
            larkUserDetailInfo.getData().put("name","非企业员工");
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),larkUserDetailInfo,authorizationDto,companyInfo,1);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(larkUserDetailInfo),10);
            return Result.failure("你不是该企业的员工");
        }
    }


    /**
     * 认证飞书小程序
     * @param map2
     * @param authorizationDto
     * @param bAuthToken
     * @param companyInfo
     * @param programmeApiBind
     * @return
     * @throws Exception
     */
    private Result authDing(Map<String, Object> map2,AuthorizationDto authorizationDto,String bAuthToken,CompanyInfo companyInfo,ProgrammeApiBind programmeApiBind) throws Exception {
        DingVo dingVo = ModelMapperUtil.strictMap(map2, DingVo.class);
        HashMap dataMap = queryMiniProgrammeService.code2Session(dingVo.getAccess_token(), authorizationDto.getCode(),2,"","");
        if (dataMap.containsKey("errcode")){
            return Result.ok().setData(dataMap);
        }
        Object object = dataMap.get("userVo");
        map2 = JsonXMLUtils.json2map(object.toString());
        DingUserVo dingUserVo = ModelMapperUtil.strictMap(map2, DingUserVo.class);
        if (dingUserVo.getResult().get("userid") != null) {
            dataMap = queryMiniProgrammeService.getUserInfo(dingVo.getAccess_token(), dingUserVo.getResult().get("userid"),2);
            if (dataMap.containsKey("errcode")){
                return Result.ok().setData(dataMap);
            }
            object = dataMap.get("userDetailInfo");
            map2 = JsonXMLUtils.json2map(object.toString());
            DingUserDetailInfo dingUserDetailInfo = ModelMapperUtil.strictMap(map2, DingUserDetailInfo.class);
            Result auth = auth(dingUserDetailInfo, authorizationDto, companyInfo,0);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(dingUserDetailInfo),2);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(dingUserDetailInfo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        } else {
            LarkUserDetailInfo larkUserDetailInfo = new LarkUserDetailInfo();
            larkUserDetailInfo.setStatus(false);
            larkUserDetailInfo.getData().put("name","非企业员工");
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),larkUserDetailInfo,authorizationDto,companyInfo,2);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(larkUserDetailInfo),10);
            return Result.failure("你不是该企业的员工");
        }
    }

    /**
     * 认证qq小程序
     * @param map2
     * @param authorizationDto
     * @param bAuthToken
     * @param companyInfo
     * @param programmeApiBind
     * @return
     * @throws Exception
     */
    private Result authQQ(Map<String, Object> map2,AuthorizationDto authorizationDto,String bAuthToken,CompanyInfo companyInfo,ProgrammeApiBind programmeApiBind) throws Exception {
        HashMap dataMap = queryMiniProgrammeService.code2Session("",authorizationDto.getCode(),6,companyInfo.getAppId(),companyInfo.getSecret());
        if (dataMap.containsKey("errcode")){
            return Result.ok().setData(dataMap);
        }
        Object object = dataMap.get("userVo");
        map2 = JsonXMLUtils.json2map(object.toString());
        QqUserVo qqUserVo = ModelMapperUtil.strictMap(map2, QqUserVo.class);
        if (qqUserVo.getOpenid() != null) {
            Result auth = auth(qqUserVo, authorizationDto, companyInfo,0);
            if (auth.getCode() == 200) {
                Map map = new HashMap();
                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qqUserVo),2);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qqUserVo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
        } else {
            QqUserVo userVo = new QqUserVo();
            userVo.setStatus(false);
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),userVo,authorizationDto,companyInfo,6);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(userVo),10);
            return Result.failure("未识别到当前用户");
        }
    }

    /**
     * 认证支付宝小程序
     * @param authorizationDto
     * @param bAuthToken
     * @param companyInfo
     * @param programmeApiBind
     * @return
     * @throws Exception
     */
    private Result authAli(AuthorizationDto authorizationDto,String bAuthToken,CompanyInfo companyInfo,ProgrammeApiBind programmeApiBind) throws Exception {
        AlipaySystemOauthTokenResponse response = queryMiniProgrammeService.getAliAccessToken(authorizationDto.getCode(),companyInfo.getAppId(),companyInfo.getAliPrivateKey(),companyInfo.getAliPublicKey());
        if (response.isSuccess()) {
            LOG.info("获取access_token - 调用成功");
            /**
             * 获取到用户信息后保存到数据
             * 1. 如果数据库不存在对用的 alipayUserId, 则注册
             * 2. 如果存在，则获取数据库中的信息再返回
             */
            String accessToken = response.getAccessToken();
            String alipayUserId = response.getUserId();

            // 获取会员信息
            AlipayUserInfoShareResponse aliUserInfo = queryMiniProgrammeService.getAliUserInfo(accessToken,companyInfo.getAppId(),companyInfo.getAliPrivateKey(),companyInfo.getAliPublicKey());
            if (aliUserInfo != null) {
                LOG.info("获取会员信息 - 调用成功");
                AliUserDetailVo userDetailVo = new AliUserDetailVo();
                userDetailVo.setAlipayUserId(alipayUserId);
                userDetailVo.setNickname(aliUserInfo.getNickName());
                userDetailVo.setAvatar(aliUserInfo.getAvatar());
                userDetailVo.setProvince(aliUserInfo.getProvince());
                userDetailVo.setCity(aliUserInfo.getCity());
                userDetailVo.setGender(aliUserInfo.getGender());

                Result auth = auth(userDetailVo, authorizationDto, companyInfo,0);
                if (auth.getCode() == 200) {
                    Map map = new HashMap();
                    redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(userDetailVo),2);
                    //认证结果
                    redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(userDetailVo),10);
                    map.put("token",bAuthToken);
                    return Result.ok().setData(map);
                }
                return auth;
            }else {
                //未查询到用户
                AliUserDetailVo userVo = new AliUserDetailVo();
                userVo.setStatus(false);
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),userVo,authorizationDto,companyInfo,7);
                //认证结果
                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(userVo),10);
                LOG.info("未识别到当前用户");
                return Result.failure("未识别到当前用户");
            }
        } else {
            LOG.info("获取access_token - 调用失败");
            Result.failure("支付宝小程序获取accessToken异常");
        }
        return Result.ok();
    }


    /**
     * 无密码方案
     * @param authorizationDto
     * @return
     */
    private Result auth(Object userDetailInfo, AuthorizationDto authorizationDto,CompanyInfo companyInfo,Integer time) throws Exception {
        //获取方案，微信账号，云管账号绑定关系
        ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
        if(null==programmeApiBind)
        {
            return Result.failure("参数错误");
        }
        //查询云管账号
        PortalUser portalUser = portalUserService.queryById(programmeApiBind.getPortalUserId());
        if (portalUser == null) {
            return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC); //认证失败
        }
        LOG.info("portal--->{}",JsonXMLUtils.obj2json(portalUser));
        // 认证授权
        String auth = auth(portalUser.getTenantName(), portalUser.getTenantPwd(), portalUser.getDomain(), authorizationDto,time);
        LOG.info("=====》"+auth);
        Integer miniType = authorizationDto.getType();
        //飞书
        if(miniType==1)
        {
            LarkUserDetailInfo larkUserDetailInfo=ModelMapperUtil.strictMap(userDetailInfo,LarkUserDetailInfo.class);

            if (auth == null) {
                larkUserDetailInfo.setStatus(false);
                //认证log
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),larkUserDetailInfo,authorizationDto,companyInfo,miniType);
                //认证失败·
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(larkUserDetailInfo),10);
            //认证log
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),larkUserDetailInfo,authorizationDto,companyInfo,miniType);
            return Result.ok();
        }else if(miniType==2)
        {
            //钉钉
            DingUserDetailInfo dingUserDetailInfo = ModelMapperUtil.strictMap(userDetailInfo, DingUserDetailInfo.class);
            if (auth == null) {
                dingUserDetailInfo.setStatus(false);
                //认证log
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),dingUserDetailInfo,authorizationDto,companyInfo,miniType);
                //认证失败
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(dingUserDetailInfo),10);
            //认证log
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),dingUserDetailInfo,authorizationDto,companyInfo,miniType);
            return Result.ok();
        }else if (3 == miniType)
        {
            //企业微信
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(userDetailInfo, QyWeiChatUserDetailVo.class);
            if (auth == null) {
                qyWeiChatUserDetailVo.setStatus(false);
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,miniType);
                //认证失败
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,miniType);
            return Result.ok();
        }else if(9 == miniType){
            LOG.info("entry 9999999");
            if (auth == null) {
                //认证失败
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            return Result.ok();
        }else if (miniType == 6)
        {
            QqUserVo qqUserVo = ModelMapperUtil.strictMap(userDetailInfo, QqUserVo.class);
            if (auth == null) {
                qqUserVo.setStatus(false);
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qqUserVo,authorizationDto,companyInfo,miniType);
                //认证失败
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qqUserVo),10);
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qqUserVo,authorizationDto,companyInfo,miniType);
            return Result.ok();
        }else if (miniType == 7)
        {
            AliUserDetailVo aliUserVo = ModelMapperUtil.strictMap(userDetailInfo, AliUserDetailVo.class);
            if (auth == null) {
                aliUserVo.setStatus(false);
                insertAuthorizationUser(programmeApiBind,new UserAuthLog(),aliUserVo,authorizationDto,companyInfo,miniType);
                //认证失败
                return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC);
            }
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(aliUserVo),10);
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),aliUserVo,authorizationDto,companyInfo,miniType);
            return Result.ok();
        }
        return Result.failure("参数有误");
    }

    /**
     * 授权终端
     * @param username
     * @param password
     * @param domain
     * @param authorizationDto
     * @return
     * @throws Exception
     */
    private String auth(String username, String password, String domain, AuthorizationDto authorizationDto,Integer time) throws Exception {
        HttpHeaders requestHeaders = queryMiniProgrammeService.getHttpHeaders();
        //获取云管的认证token
        HttpHeaders token = cloudCampusApi.getTokenRedis(username, password, domain, requestHeaders);
        LOG.info(JsonXMLUtils.obj2json(token));
        if (token == null) {
            LOG.info("nulllllllll");
            return null;
        }
        authorizationDto.setUserName(username);
        //发起授权
        LOG.info("start auth!!!{}",JsonXMLUtils.obj2json(authorizationDto));
        LOG.info("token:{}",token);
        LOG.info("domain:{}",domain);
        LOG.info("time:{}",time);
        return setAuthorizationUser(token, domain, authorizationDto,time);
    }

    /**
     * 认证日志列表
     * @param userDetailInfo
     * @param authorizationDto
     * @param companyInfo
     */
    private void insertAuthorizationUser(ProgrammeApiBind programmeApiBind,UserAuthLog userAuthLog,Object userDetailInfo, AuthorizationDto authorizationDto,CompanyInfo companyInfo,Integer miniType) throws Exception {
        userAuthLog.setId(IdUtil.getStringId());
        userAuthLog.setAuthTime(new Date());
        userAuthLog.setCompanyInfoId(companyInfo.getId());
        userAuthLog.setApMac(authorizationDto.getApmac());
        userAuthLog.setSsid(decodeToString(authorizationDto.getSsid()));
        userAuthLog.setSiteId(authorizationDto.getSiteId());
        userAuthLog.setPortalUserId(programmeApiBind.getPortalUserId());
        userAuthLog.setNodeIp(authorizationDto.getNodeIp());
        userAuthLog.setTerminalIp(authorizationDto.getUaddress());
        userAuthLog.setTerminalMac(authorizationDto.getUmac());
        userAuthLog.setProgrammeInfoId(programmeApiBind.getProgrammeInfoId());

        if (1==miniType)
        {
            LarkUserDetailInfo larkUserDetailInfo = ModelMapperUtil.strictMap(userDetailInfo, LarkUserDetailInfo.class);
            userAuthLog.setOpenId((String) larkUserDetailInfo.getData().get("open_id"));
            userAuthLog.setUserName((String) larkUserDetailInfo.getData().get("name"));
            userAuthLog.setStatus(larkUserDetailInfo.getStatus());
            userAuthLog.setIdentityType(1);
            if (larkUserDetailInfo.getData().get("open_id") == null || "".equals((String) larkUserDetailInfo.getData().get("open_id"))) {
                userAuthLog.setOpenId("1");
            }
            userAuthLogService.insert(userAuthLog);
        }else if (2==miniType)
        {
            DingUserDetailInfo dingUserDetailInfo = ModelMapperUtil.strictMap(userDetailInfo, DingUserDetailInfo.class);
            userAuthLog.setUserId((String) dingUserDetailInfo.getResult().get("userid"));
            userAuthLog.setUserName((String) dingUserDetailInfo.getResult().get("name"));
            userAuthLog.setStatus(dingUserDetailInfo.getStatus());
            userAuthLog.setIdentityType(2);
            if (dingUserDetailInfo.getResult().get("open_id") == null || "".equals((String) dingUserDetailInfo.getResult().get("open_id"))) {
                userAuthLog.setOpenId("1");
            }
            userAuthLogService.insert(userAuthLog);
        }else if(3==miniType)
        {
            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(userDetailInfo, QyWeiChatUserDetailVo.class);
            userAuthLog.setUserName(qyWeiChatUserDetailVo.getName());
            userAuthLog.setUserId(qyWeiChatUserDetailVo.getUserid());
            userAuthLog.setTelPhone(authorizationDto.getPhoneNum());
            userAuthLog.setStatus(qyWeiChatUserDetailVo.getStatus());
            if (qyWeiChatUserDetailVo.getOpenId() == null || "".equals(qyWeiChatUserDetailVo.getOpenId())) {
                userAuthLog.setOpenId("1");
            }else {
                userAuthLog.setOpenId(qyWeiChatUserDetailVo.getOpenId());
            }
            userAuthLog.setIdentityType(3);
            userAuthLogService.insert(userAuthLog);
        }else if (miniType == 6)
        {
            QqUserVo qqUserVo = ModelMapperUtil.strictMap(userDetailInfo, QqUserVo.class);
            userAuthLog.setStatus(qqUserVo.getStatus());
            userAuthLog.setOpenId(qqUserVo.getOpenid());
            userAuthLogService.insert(userAuthLog);
        }else if (miniType == 7)
        {
            AliUserDetailVo aliUserVo = ModelMapperUtil.strictMap(userDetailInfo, AliUserDetailVo.class);
            userAuthLog.setStatus(aliUserVo.getStatus());
            userAuthLog.setUserId(aliUserVo.getAlipayUserId());
            userAuthLogService.insert(userAuthLog);
        }
    }

    /**
     * 授权终端用户
     * @param requestHeaders
     * @param authorizationDto
     * @return
     * @throws Exception
     */

    private String setAuthorizationUser(HttpHeaders requestHeaders,String domain, AuthorizationDto authorizationDto,Integer time) throws Exception {
        try {
            LOG.info(">>>>>>>>come in setAuthorizationUser");
            LOG.info("ssid-->{}"+authorizationDto.getSsid());
            LOG.info("ssid-->{}"+JsonXMLUtils.obj2json(authorizationDto));
            Map map = new HashMap();
            Authorization authorizationUser = new Authorization();
            authorizationUser.setDeviceMac(authorizationDto.getApmac());
            String ssid = authorizationDto.getSsid();
            for (int i = 0 ;i< 20; i++) {
                ssid = decodeUrlToString(ssid);
            }
            if (ssid.contains(" ")) {
                ssid = ssid.replaceAll(" ","+");
            }
            LOG.info("ssid--->{}"+ssid);
            authorizationUser.setSsid(ssid);
            authorizationDto.setSsid(ssid);
            authorizationUser.setTerminalIpV4(authorizationDto.getUaddress());
            if (time!=null && time!=0)
            {
                authorizationUser.setTemPermitTime(time*60*60);
            }else {
                authorizationUser.setTemPermitTime(0);
            }
            if (authorizationDto.getNodeIp() != null) {
                authorizationUser.setNodeIp(authorizationDto.getNodeIp());
            }
            authorizationUser.setTerminalMac(authorizationDto.getUmac());
            if (authorizationDto.getUserName() != null && !"".equals(authorizationDto.getUserName())) {
                authorizationUser.setUserName(authorizationDto.getUserName());
            }
            LOG.info("authorizationUformat, argser-->{}",JsonXMLUtils.obj2json(authorizationUser));
            map = JSONObject.parseObject(JsonXMLUtils.obj2json(authorizationUser));
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_FIRST.concat(domain).concat(ApiUrlConstants.AUTHORIZATION_URL_NOT), requestEntity, JSONObject.class);
            JSONObject jsonObject = response.getBody();
            LOG.info("jsonObjec: {}",JsonXMLUtils.obj2json(jsonObject));
            return jsonObject.getString("psessionid");
        }catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取手机号
     * @param companyInfo
     * @param code
     * @return
     * @throws Exception
     */
    public String getPhoneNumber(CompanyInfo companyInfo,String code) throws Exception {
        if (redisUtil.exist(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()))) {
            String token = redisUtil.getValue(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()));
            Map<String, Object> getPhoneNumber = queryWeiChatService.getPhoneNumber(token,code);
            if (getPhoneNumber.containsKey("errcode")) {
                LOG.error("getPhoneNumErr"+JsonXMLUtils.obj2json(getPhoneNumber));
                return null;
            }
            Object weiChatResponseDto = getPhoneNumber.get("phoneNumber");
            Map<String, Object> stringObjectMap = JsonXMLUtils.json2map(weiChatResponseDto.toString());
            PhoneNumber phoneNumber = ModelMapperUtil.strictMap(stringObjectMap, PhoneNumber.class);
            return phoneNumber.getPhone_info().getPhoneNumber();
        }
        String url = queryWeiChatService.getUrlWenXinAccessToken("", companyInfo.getAppId(), companyInfo.getSecret());
        HashMap wenXinAccessToken = queryWeiChatService.getWenXinAccessToken(url);
        if (wenXinAccessToken.containsKey("errcode")) {
            LOG.error("weiXinAccessTokenErr"+JsonXMLUtils.obj2json(wenXinAccessToken));
            return null;
        }
        Object weiChatDto1 = wenXinAccessToken.get("weiChatVo");
        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(map2, WeiChatVo.class);
        redisUtil.set(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()),4,weiChatVo.getAccess_token(),2);
        Map<String, Object> getPhoneNumber = queryWeiChatService.getPhoneNumber(weiChatVo.getAccess_token(),code);
        if (getPhoneNumber.containsKey("errcode")) {
            LOG.error("getPhoneNumErr1"+JsonXMLUtils.obj2json(getPhoneNumber));
            return null;
        }
        Object weiChatResponseDto = getPhoneNumber.get("phoneNumber");
        Map<String, Object> stringObjectMap = JsonXMLUtils.json2map(weiChatResponseDto.toString());
        PhoneNumber phoneNumber = ModelMapperUtil.strictMap(stringObjectMap, PhoneNumber.class);
        return phoneNumber.getPhone_info().getPhoneNumber();
    }

    public ProgrammeApiBind getProgrammeApiBind(AuthorizationDto authorizationDto) {
        ProgrammeApiBind programmeApiBind = programmeApiBindDao.queryById(authorizationDto.getProgrammeInfoBindId());
        if (null == programmeApiBind) {
            return null;
        }
        if (programmeApiBind.getCompanyInfoId() == null || "".equals(programmeApiBind.getCompanyInfoId())) {
            return null;
        }
        return programmeApiBind;
    }
    /**
     *  获取小程序 scheme 码
     * @param authorizationDto
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public Result getUrlScheme(AuthorizationDto authorizationDto, Integer type) throws Exception {
        if (authorizationDto.getProgrammeInfoBindId() == null || authorizationDto.getProgrammeInfoBindId().equals("")) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound); // 参数错误
        }
        ProgrammeApiBind programmeApiBind = programmeApiBindDao.queryById(authorizationDto.getProgrammeInfoBindId());
        if (programmeApiBind == null) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound); // 参数错误
        }
        if (programmeApiBind.getCompanyInfoId() == null || programmeApiBind.getCompanyInfoId().equals("")) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound); // 参数错误
        }
        CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
        if (companyInfo == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        if (companyInfo.getSecret() == null || companyInfo.getSecret().equals("") || companyInfo.getAppId() == null || companyInfo.getAppId().equals("")) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC); // 参数错误
        }
        /**
         * 是否存在token
         */
        if (redisUtil.exist(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()))) {
            String token = redisUtil.getValue(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()));
            String token1 = getToken(authorizationDto);
            Map<String, Object> urlSchemeGenerate = new HashMap<>();
            if (type == 8) {
                urlSchemeGenerate = queryWeiChatService.getShareUrlSchemeGenerate(token, token1,authorizationDto.getProgrammeInfoBindId());
            }else {
                urlSchemeGenerate = queryWeiChatService.getUrlSchemeGenerate(token, token1,authorizationDto.getProgrammeInfoBindId());
            }
            if (urlSchemeGenerate.containsKey("errcode")) {
                return Result.ok().setData(urlSchemeGenerate);
            }
            Object weiChatResponseDto = urlSchemeGenerate.get("weiChatResponseDto");
            Map<String, Object> stringObjectMap = JsonXMLUtils.json2map(weiChatResponseDto.toString());
            WeiChatResponseDto weiChatResponseDto1 = ModelMapperUtil.strictMap(stringObjectMap, WeiChatResponseDto.class);
            return Result.ok().setData(weiChatResponseDto1.getOpenlink());
        }
        String url = queryWeiChatService.getUrlWenXinAccessToken("", companyInfo.getAppId(), companyInfo.getSecret());
        HashMap wenXinAccessToken = queryWeiChatService.getWenXinAccessToken(url);
        if (wenXinAccessToken.containsKey("errcode")) {
            return Result.ok().setData(wenXinAccessToken);
        }
        Object weiChatDto1 = wenXinAccessToken.get("weiChatVo");
        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(map2, WeiChatVo.class);
        redisUtil.set(companyInfo.getAppId().concat(":").concat(companyInfo.getSecret()),4,weiChatVo.getAccess_token(),2);
        String token1 = getToken(authorizationDto);
        Map<String, Object> urlSchemeGenerate = new HashMap<>();
        if (type == 8) {
            urlSchemeGenerate = queryWeiChatService.getShareUrlSchemeGenerate(weiChatVo.getAccess_token(), token1,authorizationDto.getProgrammeInfoBindId());
        }else {
            urlSchemeGenerate = queryWeiChatService.getUrlSchemeGenerate(weiChatVo.getAccess_token(), token1,authorizationDto.getProgrammeInfoBindId());
        }
        if (urlSchemeGenerate.containsKey("errcode")) {
            return Result.ok().setData(urlSchemeGenerate);
        }
        Object weiChatResponseDto = urlSchemeGenerate.get("weiChatResponseDto");
        map2 = JsonXMLUtils.json2map(weiChatResponseDto.toString());
        WeiChatResponseDto weiChatResponseDto1 = ModelMapperUtil.strictMap(map2, WeiChatResponseDto.class);
        return Result.ok().setData(weiChatResponseDto1.getOpenlink());
    }
    /**
     * 获取token
     * @param authorizationDto
     * @return
     * @throws Exception
     */
    public String getToken(AuthorizationDto authorizationDto) throws Exception {
        String s = getToken(16);
        redisUtil.set(s,1,JsonXMLUtils.obj2json(authorizationDto),30);
        LOG.info("redisToken--------------------------"+s);
        return s;
    }

    @Override
    public Result getDingDingToken(AuthorizationDto authorizationDto) throws Exception {
        String s = getToken(16);
        redisUtil.set(s,1,JsonXMLUtils.obj2json(authorizationDto),5);
        return Result.ok().setData(s);
    }

    /**
     * 授权企业应用
     * @param authorizationDto
     * @param bAuthToken
     * @return
     * @throws Exception
     */
    @Override
    public Result authUserByQYApp(String code, String bAuthToken,String redisToken) throws Exception {
        if (!redisUtil.exist(redisToken)){
            return Result.failure("认证参数不存在");
        }
        AuthorizationDto authorizationDto = ModelMapperUtil.strictMap(redisUtil.get(redisToken), AuthorizationDto.class);
        authorizationDto.setCode(code);
        authorizationDto.setType(9);
        LOG.info("authDto--->{}",JsonXMLUtils.obj2json(authorizationDto));

        Map<Integer, String> checkMap = checkAuthData(authorizationDto);
        if (checkMap.containsKey(0)){
            return Result.failure(checkMap.get(0));
        }
        ProgrammeApiBind programmeApiBind = getProgrammeApiBind(authorizationDto);
        if (programmeApiBind == null) {
            return Result.failure(QY_NOT_CONFIG,QY_NOT_CONFIG_DESC);
        }

        if (bAuthToken != null && !bAuthToken.equals("")) {
            if (!redisUtil.exist(bAuthToken)) {
                LOG.info("1");
                return getQyAppResult(bAuthToken,programmeApiBind,authorizationDto);
            }

            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = JsonXMLUtils.json2obj(redisUtil.getValue(bAuthToken), QyWeiChatUserDetailVo.class);
            if (qyWeiChatUserDetailVo.getUserid() != null) {
                LOG.info("2");
                CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
                Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,authorizationDto.getTime());
                if (auth.getCode() == 200) {
                    LOG.info("5");
                    Map map = new HashMap();
                    redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                    //认证结果
                    redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                    map.put("token",bAuthToken);
                    return Result.ok().setData(map);
                }
                LOG.info("6");
                return auth;
            }
            LOG.info("3");
            CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
            //访客突然成为企业微信的员工则需要查询其身份并授权
            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
            //认证结果
            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
            return Result.failure("你不是该企业的员工");
        }else {
            LOG.info("4");
            bAuthToken = UserTokenManager.generateToken(authorizationDto.getCode());// 新增用户
            LOG.info(JsonXMLUtils.obj2json(authorizationDto));
            return getQyAppResult(bAuthToken, programmeApiBind,authorizationDto);
        }
    }

    @Override
    public Result saveParam(AuthorizationDto authDto) throws Exception {
        String token = getToken(authDto);
        return Result.ok().setData(token);
    }

    /**
     * 校验企业微信应用
     * @return
     */
    public Result getQyAppResult(String bAuthToken,ProgrammeApiBind programmeApiBind,AuthorizationDto authorizationDto) throws Exception {
        //获取企业信息
        CompanyInfo companyInfo = companyInfoDao.queryById(programmeApiBind.getCompanyInfoId());
        LOG.info("7-->{}",companyInfo);
        //获取access_token
//        String accessTokenUrl = queryWeiChatService.getUrl("", companyInfo.getCorpId(), companyInfo.getSecret());
//        HashMap openId = queryWeiChatService.getOpenId(accessTokenUrl);
//        if (openId.containsKey("errcode")) {
//            return Result.ok().setData(openId);
//        }
//        Object weiChatDto1 = openId.get("weiChatDto");
//        Map<String, Object> map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
//        WeiChatVo weiChatVo = ModelMapperUtil.strictMap(map2, WeiChatVo.class);
//        获取用户id
//        openId = queryWeiChatService.getUserInfo(weiChatVo.getAccess_token(), authorizationDto.getCode());
//        if (openId.containsKey("errcode")){
//            LOG.info("get userInfo error!!!"+openId);
//            return Result.ok().setData(openId);
//        }
//        weiChatDto1 = openId.get("qyWeiChatUserVo");
//        map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
//        QyWeiChatUserVo qyWeiChatUserVo1 = ModelMapperUtil.strictMap(map2, QyWeiChatUserVo.class);
//        if (qyWeiChatUserVo1.getUserid() != null) {
//            openId = queryWeiChatService.getUser(weiChatVo.getAccess_token(), qyWeiChatUserVo1.getUserid());
//            if (openId.containsKey("errcode")){
//                return Result.ok().setData(openId);
//            }
//            weiChatDto1 = openId.get("qyWeiChatUserDetailVo");
//            map2 = JsonXMLUtils.json2map(weiChatDto1.toString());
//            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = ModelMapperUtil.strictMap(map2, QyWeiChatUserDetailVo.class);
//            qyWeiChatUserDetailVo.setAccess_token(weiChatVo.getAccess_token());
//            qyWeiChatUserDetailVo.setDeviceId("1");
//            qyWeiChatUserDetailVo.setStatus(true);
//            qyWeiChatUserDetailVo.setQyCorpInfoId(companyInfo.getId());
//            qyWeiChatUserDetailVo.setPortalUserId(programmeApiBind.getPortalUserId());
//            Result auth = auth(qyWeiChatUserDetailVo, authorizationDto, companyInfo,authorizationDto.getTime());
            Result auth = auth(null, authorizationDto, companyInfo,authorizationDto.getTime());
            LOG.info("auth--->{}",JsonXMLUtils.obj2json(auth));
            if (auth.getCode() == 200) {
                Map map = new HashMap();
//                redisUtil.set(bAuthToken,4,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),2);
                //认证结果
//                redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
                map.put("token",bAuthToken);
                return Result.ok().setData(map);
            }
            return auth;
//        } else {
//            QyWeiChatUserDetailVo qyWeiChatUserDetailVo = new QyWeiChatUserDetailVo();
//            qyWeiChatUserDetailVo.setStatus(false);
//            qyWeiChatUserDetailVo.setDeviceId("2");
//            qyWeiChatUserDetailVo.setName("非企业员工");
//            insertAuthorizationUser(programmeApiBind,new UserAuthLog(),qyWeiChatUserDetailVo,authorizationDto,companyInfo,3);
            //认证结果
//            redisUtil.set(authorizationDto.getApmac().concat(authorizationDto.getUmac()).concat(authorizationDto.getSsid()).concat("auth"),1,JsonXMLUtils.obj2json(qyWeiChatUserDetailVo),10);
//            return Result.failure("你不是该企业的员工");
//        }


    }

    /**
     * 企业微信认证校验认证参数
     * @param authDto 认证参数dto
     * @return map集合
     */
    public Map<Integer, String> checkAuthData(AuthorizationDto authDto){
        Map<Integer, String> map = new HashMap<>();
        if (authDto.getProgrammeInfoBindId() == null || authDto.getProgrammeInfoBindId().equals("")){
            map.put(0,"方案绑定id为空");
        }else if (authDto.getApmac() == null || authDto.getApmac().equals("")){
            map.put(0,"apMac为空");
        }else if (authDto.getSsid() == null || authDto.getSsid().equals("")){
            map.put(0,"ssid为空");
        }else if (authDto.getUaddress() == null || authDto.getUaddress().equals("")){
            map.put(0,"终端IPv4地址为空");
        }else if (authDto.getNodeIp() == null || authDto.getNodeIp().equals("")){
            map.put(0,"授权节点地址为空");
        }else if (authDto.getUmac() == null || authDto.getUmac().equals("")){
            map.put(0,"终端MAC为空");
        }else {
            map.put(1,"");
        }
        return map;
    }

    private String getToken(int i) {
        String charAndNumr = getCharAndNumr(i);
        if (redisUtil.exist(charAndNumr)) {
            charAndNumr = getToken(i);
        }
        return charAndNumr;
    }
}
